package com.jingzhi.huimiao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

import com.google.gson.Gson;
import com.jingzhi.huimiao.base.BaseActivity;
import com.jingzhi.huimiao.bean.Test;
import com.jingzhi.huimiao.bean.User;
import com.jingzhi.huimiao.utils.CanstantUtils;
import com.jingzhi.huimiao.utils.HttpUtils;

/**
 * 注册界面
 * 
 * @author cxk
 * 
 */
public class RegistActivity extends BaseActivity implements OnClickListener {
	private String result;
	private String username;
	private ImageView iv_toweixin;

	private String phString;// 验证码

	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.activity_regist);

		iv_toweixin = (ImageView) findViewById(R.id.iv_toweixin);

		SMSSDK.initSDK(this, "ecd184700829", "5769643dfacd05ae6ebcc90e6c705797");

		initSMSSDK();

		iv_toweixin.setOnClickListener(this);

	}

	/**
     * 判断是否为手机号
     */

    private boolean isPhone(String mobilenumber) {
        Pattern p = Pattern
                .compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
        Matcher m = p.matcher(mobilenumber);
        return m.matches();
    }
	
	/**
	 * 短信验证码注册
	 */
	private void initSMSSDK() {
		EventHandler eh = new EventHandler() {

			@Override
			public void afterEvent(int event, int result, Object data) {

				Message msg = new Message();
				msg.arg1 = event;
				msg.arg2 = result;
				msg.obj = data;
				handler.sendMessage(msg);
			}

		};
		SMSSDK.registerEventHandler(eh); // 注册短信回调

	}
	
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			int event = msg.arg1;
			int result = msg.arg2;
			Object data = msg.obj;
			Log.e("event", "event=" + event);
			if (result == SMSSDK.RESULT_COMPLETE) {
				// 短信注册成功后，返回MainActivity,然后提示新好友
				if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {// 提交验证码成功
					Toast.makeText(RegistActivity.this, "提交验证码成功", 0).show();
				} else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
					Toast.makeText(RegistActivity.this, "验证码已经发送", 0).show();
				}
			} else {
				((Throwable) data).printStackTrace();
				Toast.makeText(RegistActivity.this, "验证码错误", 0).show();
			}
		};
	};

	// 重写父类中监听方法
	@Override
	public void setListener() {
		// 给登录按钮设置监听，进入登录页面
		btn_next.setOnClickListener(new RegistOnClickListener());
		// 给返回键设置监听。重回注册页面
		iv_back.setOnClickListener(new RegistOnClickListener());
		// 对输入的用户名设置监听，判断是否重名
		et_name.setOnFocusChangeListener(new View.OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (!hasFocus) {
					username = et_name.getText().toString().trim();
					// 用于捕获磁盘访问或者网络访问中与主进程之间交互产生的问题
					StrictMode
							.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
									.detectDiskReads().detectDiskWrites()
									.detectNetwork().penaltyLog().build());
					StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
							.detectLeakedSqlLiteObjects()
							.detectLeakedClosableObjects().penaltyLog()
							.penaltyDeath().build());

					Map<String, String> uninfo = new HashMap<String, String>();
					uninfo.put("username", username);
					try {
						String retName = HttpUtils.sendPostRequest(
								CanstantUtils.usernameYan_url, uninfo, "utf-8");
						Log.e("TAG------", retName);
						Gson gson = new Gson();
						Test result = gson.fromJson(retName, Test.class);

						if ("success".equals(result.getFan().toString())) {
							Toast.makeText(RegistActivity.this, "用户名可用", 0)
									.show();
							btn_next.setClickable(true);
							btn_next.setBackgroundResource(R.drawable.btn_login_bg);
						} else {
							Toast.makeText(RegistActivity.this, "用户名已存在", 0)
									.show();
							btn_next.setClickable(false);
							btn_next.setBackgroundColor(Color.GRAY);

						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		});

	}

	class RegistOnClickListener implements OnClickListener {

		ArrayList<User> users = new ArrayList<User>();
		private String password;

		public void dialog() {
			username = et_name.getText().toString().trim();

			// 创建对话框对象
			new AlertDialog.Builder(RegistActivity.this)
					.setTitle("登录")
					.setMessage("请确认您的手机号码为:" + username)
					.setPositiveButton("确认",
							new DialogInterface.OnClickListener() {

								private SQLiteDatabase db;

								@Override
								public void onClick(DialogInterface dialog,
										int which) {

									saveInfo();
									/*
									 * // 打开数据库输出流 SQLdm s = new SQLdm(); db =
									 * s.openDatabase(getApplicationContext());
									 * ContentValues v = new ContentValues();
									 * v.put("word_id", 1); v.put("user_id",
									 * username); db.insert("role1",null, v);
									 * db.insert("role2",null, v);
									 * db.insert("role3",null, v);
									 */
									startActivity(new Intent(
											RegistActivity.this,
											LoginActivity.class));
									finish();
								}
							})
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									Toast.makeText(RegistActivity.this, "未登录",
											0).show();
								}
							}).show();
		}

		@Override
		public void onClick(View v) {
			switch (v.getId()) {

			case R.id.btn_next:
				username = et_name.getText().toString().trim();
				password = et_password.getText().toString().trim();
				if ("".equals(password) || "".equals(username)) {
					Toast.makeText(RegistActivity.this, "用户名或密码不能为空！", 0)
							.show();
					break;
				}
				dialog();

				break;
			case R.id.iv_back:

				startActivity(new Intent(RegistActivity.this,
						RegistActivity.class));

				finish();
				break;
			
			

			default:
				break;
			}
		}

		public void saveInfo() {
			username = et_name.getText().toString().trim();
			password = et_password.getText().toString().trim();

			// 用于捕获磁盘访问或者网络访问中与主进程之间交互产生的问题
			StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
					.detectDiskReads().detectDiskWrites().detectNetwork()
					.penaltyLog().build());
			StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
					.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
					.penaltyLog().penaltyDeath().build());

			// 将用户信息存放在Map中
			Map<String, String> userinfo = new HashMap<String, String>();
			userinfo.put("username", username);
			userinfo.put("password", password);
			try {
				String retStr = HttpUtils.sendPostRequest(
						CanstantUtils.regist_url, userinfo, "utf-8");
				// Log.e("TAG------", retStr);
				Gson gson = new Gson();
				Test result = gson.fromJson(retStr, Test.class);
				if ("success".equals(result.getFan().toString())) {
					Toast.makeText(RegistActivity.this, "注册成功", 0).show();
				} else {
					Toast.makeText(RegistActivity.this,
							result.getFan().toString(), 0).show();
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();

		SMSSDK.unregisterAllEventHandler();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.iv_toweixin:

			String regist_phoneNumber = et_name.getText().toString();
			if (!TextUtils.isEmpty(regist_phoneNumber)
					&& isPhone(regist_phoneNumber)) {
				SMSSDK.getVerificationCode("86", regist_phoneNumber);
				phString = regist_phoneNumber;
			} else {
				Toast.makeText(RegistActivity.this, "请输入正确的手机号", 0).show();
			}
			break;	

		default:
			break;
		}
	}
}
